const mongoose = require('mongoose');
const { mongod } = require('../config');
const Grid = require('gridfs-stream');
const logUtil = require('./log_util');

let gfs = null;
Grid.mongo = mongoose.mongo;


mongoose.connection.once('open', () => {
  logUtil.info('mongodb connection opened');
  gfs = Grid(mongoose.connection.db);
  // console.info('gfs is ', gfs);
});
mongoose.connection.on('error', (err) => {
  logUtil.error('mongodb connection error', err);
  process.exit();
});

mongoose.connect(mongod.uri, mongod.options, () => {
  logUtil.info('connect to mongodb success');
});

module.exports = {
  mongoose,
  gridFs() {
    return new Promise((res, rej) => {
      if (gfs) res(gfs);
      //如果数据库连接没有启动，需求强制启动连接
      mongoose.connect(mongod.uri, mongod.options, (err) => {
        if (err) rej(err);
        res(gfs);
      });
    });
  }
};
